import base from './base';
import React from 'react';
// import * as MonitorUtil from './MonitorUtil';
import { getLabel, showConfirm } from './common';
//import {closeQYSAuth} from "./secondAuthUtil";

let emClient = null;

const emJsApis = [
    'showBottomToolBar', 'hideBottomToolBar',
    'configNavigation', 'resetNavigation', 'previewImage',
    'handleWriting', 'chooseImage', 'getLocalImgData',
    'editImage', 'getLocationList', 'getAudioRecord', 'openLocation',
    'speechTotext', 'userInteractionEnabled', 'userInteractionDisabled',
    "fileSign", "getFileFormatCanSign", "getFlowHandwrite", "saveFlowHandwrite",
    "deleteFlowHandwrite","closeWindow"
];
/**
 * 表单加载校验当前版本支持哪些API，存variableMap
 * @param {校验的API数组} apis
 */
export const verifyEmSDK = () => {
    if (!window.em) return;
    const updateParams = {};
    const params = { 'jsApiList': emJsApis };
    params.success = (args = {}) => {
        let result = args;
        if (typeof args === 'string') result = JSON.parse(args);
        const { checkResult = {} } = result;
        emJsApis.map((k) => {
            updateParams[`em_${k}`] = checkResult[k] || false;
            if (k === "getFileFormatCanSign" && checkResult[k]) {
                getFileFormatCanSign();
            }
        })
        base.wfGlobalStore.batchControlVariableMap(updateParams);
    };
    //同步接口
    window.em.checkJsApi(params);
    emClient = window.em;
}
export { emClient }

//页面标题
export const getPageTitle = () => {
    let pageTitle = "";
    const { wfGlobalStore, wfLayoutStore } = base;
    const { commonParam } = wfGlobalStore;
    const { mainData } = wfLayoutStore;
    const { iscreate, workflowname } = commonParam;
    if (!commonParam && parseInt(iscreate) === 1) {
        pageTitle = `${getLabel(83443, '创建')} - ${workflowname}`;
    } else if (mainData.has("field-1")) {
        pageTitle = mainData.get("field-1").value;
    } else {
        pageTitle = `${getLabel(553, '处理')} - ${workflowname}`;
    }
    return pageTitle;
}

/**
 * 判断em指定接口是否可以使用
 * @param {API名称} apiname
 * @return true:支持 false 不支持
 */
export const judgeApiSupport = (apiname) => {
    const { variableMap } = base.wfGlobalStore;
    return window.em && variableMap.has(`em_${apiname}`) && variableMap.get(`em_${apiname}`);
}

//控制底部按钮（表单中）
export const controlBottomBtn = (nextPathname = '', operator) => {//在一些点击事件上执行这个方法
    const { controlVariableMap } =  base.allStores.wfSignInputStore;
    if ((nextPathname === '/req' || (nextPathname === '/req/intervenor' && operator)) && judgeApiSupport('showBottomToolBar')) {
        let btns = [];
        // if (nextPathname === '/req/intervenor') {
        //     btns = MonitorUtil.getEmBottomBtns();
        // }
        if (btns.length === 0) return;
        let emBtnParams = {
            'items': btns,
            'success': (argument) => {
                controlVariableMap("isShowEmBottomBtn",true)
                console.log('controlShowBottomBtn-success', argument, emBtnParams);
            },
            'fail': (argument) => {
                console.log('controlShowBottomBtn-fail', argument)
            }
        };
        emClient.hideBottomToolBar({
            'success': (arg) => {
                controlVariableMap("isShowEmBottomBtn",false)
                console.log('controlHideBottomToolBar-success', arg);
            }
        });
        emClient.showBottomToolBar(emBtnParams);
    }
}

//保存手写签批痕迹
export const saveFlowHandwrite = (workflowid) => {
    //客户端说em.checkJsApi("xxx")这种方式是判断jem.js是否支持的，em.chekcJsApi({jsApiList:[],success:(){}})这种方式是判断app是否支持的
    if(judgeApiSupport("saveFlowHandwrite") && emClient.checkJsApi("saveFlowHandwrite")){
        emClient.saveFlowHandwrite({
            workflowid:workflowid,
            success: function (res) {
                console && console.log("保存手写签批痕迹",res)
            }
        });
    }else{
        console && console.log("em不支持saveFlowHandwrite")
    }
}

//获取手写签批痕迹
export const getFlowHandwrite = (workflowid) => {
    if(judgeApiSupport("getFlowHandwrite") && emClient.checkJsApi("getFlowHandwrite")){
        emClient.getFlowHandwrite({
            workflowid: workflowid,
            success: function (argument) {
                let result = getEmResultData(argument);
                const { localExist  = false } = result;
                const { controlVariableMap } =  base.allStores.wfSignInputStore;
                controlVariableMap("localExist",localExist)
                console && console.log("获取手写签批痕迹",localExist)
            }
        });
    }else {
        console && console.log("em不支持getFlowHandwrite")
    }
}

//删除本地流程签批
export const deleteFlowHandwrite = (workflowid) => { 
    if(judgeApiSupport("deleteFlowHandwrite") && emClient.checkJsApi("deleteFlowHandwrite")){
        emClient.deleteFlowHandwrite({
            workflowid:workflowid,
            success: function (res) {
                console && console.log("删除本地流程签批",res)
            }
        });
    }else {
        console && console.log("em不支持deleteFlowHandwrite")
    }
}

export const continueSpeech = () => {
    emClient.continueSpeech({
        'changeVoice':
            arg => {
                //音量变化回调  int 0-100 一般在50左右
                console.log('changeVoice')
            },
        'continueSpeechend': arg => {
            //{"result":"今天天气怎样？","errMsg":"服务正常","clientType":"iPhone","errCode":0},"handlerName":"continueSpeechend"}
            //语音识别结束 为对象result为识别后的文字 调用一次
        },
        'onContinueSpeech': arg => {
            //{"result":"喂喂","errMsg":"onContinueSpeech:ok","clientType":"iPhone","errCode":0}
            //识别过程中，持续识别，多次调用，同个会话中，后面解析的文字，将会追加在之前的一起返回
        },
        'success':
            arg => {
                //方法 成功响应
            },
        'fail': arg => {
            //识别出错
        },
        'cancel': arg => {

        },
        'complete': arg => {
            //完成
        }
    })
}



//签批替换原文件
const replaceDeaultFile = (res, flag, fieldStore,docid) => {
    const { odocInfo = {} } = base.wfLayoutStore;
    const { imagefileId : odocInfo_imagefileId = "", mobileInfo={} } = odocInfo;
    const { isShowDocTab,addressUrl="" }=mobileInfo;
    const { imagefileId } = res;
    base.wfGlobalStore.batchControlVariableMap({ [`imagefiledId_${flag}`]: imagefileId });
    if(fieldStore){
        let {datas}=fieldStore;
        datas.map(item=>{
            if(item.fileid == docid){
                const{imagefileid:oldImagefileid}=item;
                item.filelink = item.filelink.replace(oldImagefileid,imagefileId);
                item.loadlink = item.loadlink.replace(oldImagefileid,imagefileId);
                item.imagefileid = imagefileId;
            }
        })
        fieldStore.setState({datas:datas})
    }
    //有正文的情况,且签批的是正文，还要更新正文tab下src
    if((odocInfo_imagefileId != imagefileId) && isShowDocTab && flag == odocInfo_imagefileId ){
        base.wfGlobalStore.controlVariableMap("wf-odocSrc",addressUrl.replace(odocInfo_imagefileId,imagefileId));
    }
}


//是否显示签批按钮的权限判断
export const checkShowSignBtn = (fileExtendName,viewAttr,isannexupload_edit) => {
    if (fileExtendName && fileExtendName.includes(".")) fileExtendName = fileExtendName.split(".")[1];
    if(fileExtendName != "pdf"){
        return true;
    }
    let show=false;
    const { variableMap } = base.wfOperateStore;
    let mobilePDFSign = variableMap.has("mobilePDFSign") ? variableMap.get("mobilePDFSign") : "0";
    /**
        A、写入流转意见
        B、替换原文件
        C、由用户自己选择
        三、再根据权限判断是否显示签批按钮及签批模式
        1、配置二选择A，如果用户没有意见附件上传权限，则不显示签批按钮
        2、配置二选择B，如果用户没有字段编辑权限，则不显示签批按钮
        3、配置二选择C：
        如果有字段编辑权限viewAttr，没有意见附件上传权限isannexupload_edit，则只能是替换，不弹出选择；
        如果无字段编辑权限，有意见附件上传权限，则只能附加到意见，不弹出选择；
        既有字段编辑权限，又有意见附件上传权限时，才弹出选择，由用户选择是替换还是附加；
        两个权限都没有，不能签批。
    */
    if(mobilePDFSign == 1 && isannexupload_edit){//写入流转意见
        show=true;
    }else if(mobilePDFSign == 2 && viewAttr > 1){//替换原文件
        show=true;
    }else if(mobilePDFSign == 3 && (viewAttr > 1 || isannexupload_edit)){//由用户自己选择
        show=true;
    }
    return show;
}

//获取当前file中的loadlink中的参数,并改变参数中的fileid;
export const changeFileid = (file) => {
    const { variableMap } = base.wfGlobalStore;
    const { commonParam } = base.wfGlobalStore;
    const { wfSignInputStore } = base.allStores;
    const { requestid, authStr, authSignatureStr, f_weaver_belongto_userid, f_weaver_belongto_usertype } = commonParam;
    const imagefileId = variableMap.has(`imagefiledId_${file.imagefileid}`) ? variableMap.get(`imagefiledId_${file.imagefileid}`) : file.imagefileid;
    if (imagefileId != file.imagefileid) {
        file.loadlink = changeURLArg(file.loadlink, "fileid", imagefileId);
    }
}

/* 
* url 目标url 
* arg 需要替换的参数名称 
* arg_val 替换后的参数的值 
* return url 参数替换后的url 
*/
export const changeURLArg = (url, arg, arg_val) => {
    let pattern = arg + '=([^&]*)';
    let replaceText = arg + '=' + arg_val;
    if (url.match(pattern)) {
        let tmp = '/(' + arg + '=)([^&]*)/gi';
        tmp = url.replace(eval(tmp), replaceText);
        return tmp;
    } else {
        if (url.match('[\?]')) {
            return url + '&' + replaceText;
        } else {
            return url + '?' + replaceText;
        }
    }
}

//判断是否可以有【签批】按钮
/**
 * @right:当前用户拥有的权限
 * @SuffixName:文件后缀名
 */
export const checkSigningBatch = (right, SuffixName) => {
    const { variableMap } = base.wfGlobalStore;
    const filetype_list = variableMap.get("QP_formatList") || [];
    if (SuffixName && SuffixName.includes(".")) SuffixName = SuffixName.split(".")[1];
    right = SuffixName !== "pdf" ? right : true;
    if (filetype_list && filetype_list.length > 0 && filetype_list.includes(SuffixName) && right) {
        return true;
    } else {
        return false;
    }
}


//获取支持文件签批的格式
export const getFileFormatCanSign = () => {
    emClient.getFileFormatCanSign({
        success: function (res) {
            // 返回结果
            if (typeof res === "string") {
                res = JSON.parse(res);
            }
            const { formatList, errCode } = res;
            if (errCode == 0) {
                base.wfGlobalStore.batchControlVariableMap({ QP_formatList: formatList });
            }
        }
    });
}

//拍照
export const takePhoto = () => {
    emClient.chooseImage({
        'success': (argument) => {
            console.log('chooseImage-success', argument);
            let result = getEmResultData(argument);
            const { localIds = [] } = result;
            if (localIds.length > 0) {
                emClient.getLocalImgData({
                    'localId': localIds[0],
                    'success': (arg) => {
                        console.log(arg);
                    }
                })
            }
        },
        'fail': (argument) => {
            console.log('chooseImage-fail', argument);
        },
        'sourceType': ['camera']
    })
}


//录音
export const audioRecord = () => {
    const { saveSignAnnex } = base.allStores.wfSignInputStore;
    emClient.getAudioRecord({
        'success': (argument) => {
            const result = getEmResultData(argument);
            const { localData = '' } = result;
            console.log("audioRecord result :", result);
            saveSignAnnex(1, localData);
        },
        'fail': (argument) => {
            console.log('audioRecord-fail', argument);
        }
    })
}

//打开位置
export const openLocation = (params = {}) => {
    emClient.openLocation({
        ...params,
        'scale': 4,
        'success': (argument) => {
            console.log('openLocation-success', argument)
        },
        'fail': (argument) => {
            console.log('openLocation-fail', argument)
        }
    })
}



export const resetBottomBtn = () => {
    if (judgeApiSupport('hideBottomToolBar')) {
        emClient.hideBottomToolBar({
            'success': (argument) => {
                const { controlVariableMap } =  base.allStores.wfSignInputStore;
                controlVariableMap("isShowEmBottomBtn",false)
                console.log('controlHideBottmBtn-success', argument);
            },
            'fail': (argument) => {
                console.log('controlHideBottmBtn-fail', argument);
            }
        });
        
    }
    
   
}

//定制EM表单的头
export const setReqEmTopNav = (pathname, title = "") => {
    const isReq = pathname === "/req" && window.top.location.href.indexOf("/hoverWindow") === -1;
    const isQYSAuth = pathname === "/req/qysauth";
    const { commonParam={} } = base.wfGlobalStore;
    const onlyShow = parseInt(commonParam.isviewonly || 0) === 1 || parseInt(commonParam.isaffirmance || 0) === 1;

    let topTitle = getLabel(500244, "表单详情");
    if (title === "") {
        const routeMapTitle = {
            "/req": getPageTitle(),
        }
        topTitle = routeMapTitle[pathname];
        //TODO-不直接加载上面的routeMapTitle 的原因是见下面注释
        if (topTitle == null) {
            //表单路由是'req/附件id_uploadadjustment'签字意见附件路由是 '/req/annexList/uploadadjustment'
            if (pathname.indexOf("uploadadjustment") != -1) {
                topTitle = getLabel(506370, "显示调整");
            }
            //理由同上
            if (pathname.indexOf("uploadadjustment/resetname") != -1) {
                topTitle = getLabel(131615, "重命名");
            }
        }
    } else {
        topTitle = title;
    }
    controlEmTopNav({
        title: topTitle,
        // left: {
        //     'name': getLabel(1290, '返回'),
        //     'action': function (argument) {
        //         if (isReq && window.location.href.indexOf("/spa/workflow/static4mobileform") > -1) {
        //             FormUtil.returnSourcePage({ isReturn: true });
        //         } else {
        //             try {
        //                 window.historyRoute.go(-1);

        //                 //契约锁认证，关闭时，做一些特殊的处理
        //                 if (isQYSAuth) {
        //                     closeQYSAuth();
        //                 }
        //             } catch (e) {
        //                 window.close();     //a标签打开超链接情况
        //             }
        //         }
        //     }
        // }
    });
}

/**
 * 控制EM客户端顶部头信息
 */
export const controlEmTopNav = (params = {}) => {
    document.title = params.title ? params.title : "";//和飞信中走此段
    if (!judgeApiSupport("configNavigation")) {
        return;
    }
    const nav = {
        'success': function (argument) {
            console.log('controlEmTopNav success', JSON.stringify(argument));
        },
        'fail': function (argument) {
            console.log('controlEmTopNav fail', JSON.stringify(argument));
        },
        'left': {},
        'right': {},
        'title': getLabel(500244, '表单详情'),
        showCloseButton: false
    };
    emClient.ready(function () {
        if (params.title === undefined) {
            params.title = getLabel(500244, '表单详情');
        }
        emClient.configNavigation({ ...nav, ...params });//微信中走此段
    });
}

/**
 * EM点击预览图片队列
 */
export const preViewImage = (params = {}) => {
    if (!judgeApiSupport("previewImage"))
        return;
    const base = {
        'success': function (argument) {
            console.log('preViewImage success', JSON.stringify(argument));
        },
        'fail': function (argument) {
            console.log('preViewImage fail', JSON.stringify(argument));
        },
        'urls': [],
        'current': ''
    };
    emClient.previewImage({ ...base, ...params });
}


/**
 *
 * @param argument
 * @return {*}
 */
const getEmResultData = (argument) => {
    let data = argument;
    if (typeof argument == 'string') data = JSON.parse(argument);
    return data;
}


/**
 * 打开新建短信页面 
 */
export const openSendMsg = (requestid) => {
    window.openLink.openSendMsg(requestid)
}

/**
 * 打开新建邮件页面 
 */
export const openSendEmail = (requestid) => {
    window.openLink.openSendEmail(requestid)
}

export const closeWindow = () => {
    if (judgeApiSupport('closeWindow')) {
        emClient.closeWindow();
    }
}